package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {

        //TODO 1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);

        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();

        return catalogJson;
    }

//    @GetMapping
//    public String hello(){
//
//    }

    //保证一定能读到最新的数据,修改期间，写锁就是一个排它锁(互斥锁)，读锁是一个共享锁
    //写锁没释放 读锁就必须等待 写锁释放
    //读 + 读：相当于无锁,并发读，只会在redis中记录好，所有当前的读锁，他们都同时加锁成功
    //写 + 读：等待写锁释放
    //写 + 写：阻塞方式 等写锁释放了 才能再写
    //读 + 写： 有读锁 写也需要等待
    //只要有写的存在，其他都必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            //1、该数据加写锁，读数据加读锁

            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }


        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            Thread.sleep(30000);
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }


        return s;
    }

    /**
     * 信号量
     *
     * 车库停车
     * 3号车位
     * 信号量也可以用作分布式限流
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");//信号量
        //ark.acquire();  //获取一个信号 获取一个值,占一个停车位,占满了就需要释放
        boolean b = park.tryAcquire(); //能获取信号量就返回true，不能就false

        return "ok"+b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");//信号量
        park.release();  //释放一个信号量，释放一个停车位

        return "ok";
    }

    /**
     * 放假，锁门
     * 1班没人了，2班没人了
     * 5个班全部走完，我们可以锁大门了
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();  //等待闭锁都完成

        return "放假了。。。。。。";
    }

    @GetMapping("/gogogo/{}id")
    @ResponseBody
    public String gogogo(@PathVariable("id")Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();  //计数减一

        return id+"班的人都走了。。。。。。";
    }
}
